<template>
  <up-modal
    :show="showModal"
    title="修改密码"
    confirmText="确认"
    showCancelButton
    @confirm="confirmUpdate"
    @cancel="closeModal">
    <up-form
      labelPosition="top"
      :model="pwdForm"
      :rules="pwdRules"
      labelWidth="100"
      ref="pwdRef">
      <up-form-item label="原密码" prop="password">
        <up-input
          v-model="pwdForm.password"
          placeholder="请输入原密码"></up-input>
      </up-form-item>
      <up-form-item label="新密码" prop="newPassword">
        <up-input
          v-model="pwdForm.newPassword"
          type="password"
          placeholder="请输入新密码"></up-input>
      </up-form-item>
      <up-form-item label="再次输入" prop="reNewPwd">
        <up-input
          v-model="pwdForm.reNewPwd"
          type="password"
          placeholder="请再次输入新密码"></up-input>
      </up-form-item>
    </up-form>
  </up-modal>
  <view class="container">
    <view class="header-avatar">
      <image
        :src="
          formModel.avatar
            ? 'http://localhost:8080/api/avatar/' + formModel.avatar
            : '../../static/defaultAvatar.jpg'
        "
        @click="changeAvatar"></image>
    </view>
    <view class="info-form">
      <!-- 表单 -->
      <up-form labelPosition="left" :model="formModel" ref="formRef">
        <up-form-item
          label="用户名"
          prop="username"
          borderBottom
          label-width="100rpx">
          <up-input
            v-model="formModel.username"
            border="none"
            clearable></up-input>
        </up-form-item>
        <up-form-item label="手机号" borderBottom label-width="100rpx">
          {{ phone.replace(phone.substring(3, 7), '****') }}
        </up-form-item>
        <up-form-item
          label="密码"
          borderBottom
          label-width="100rpx"
          @click="updatePwd">
          修改密码
        </up-form-item>
      </up-form>
      <view class="confirmBtn" @click="submitChange">
        <text>提交修改</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue'
import { useUserStore } from '../../stores/user.js'
import { updateUserInfo, updatePwdService } from '../../api/user.js'
const userStore = useUserStore()
const { userInfo } = JSON.parse(uni.getStorageSync('user'))
let { avatar, password, phone, userId, username } = { ...userInfo }
// 用户的token
const token = userInfo.token

// 弹出层
const showModal = ref(false)

// 用户信息表单
const formModel = ref({
  avatar,
  username,
  password,
  userId,
  phone,
  token,
})
// 密码表单
const pwdRef = ref()
const pwdForm = ref({
  userId,
  password: '',
  newPassword: '',
  reNewPwd: '',
})
// 密码表单校验
// 校验二次输入密码
const validRePwd = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入新密码'))
  } else if (value !== pwdForm.value.newPassword) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}
const pwdRules = {
  password: {
    required: true,
    message: '请输入原密码',
    trigger: ['blur', 'change'],
  },
  newPassword: {
    required: true,
    message: '请输入新密码',
    trigger: ['blur', 'change'],
  },
  reNewPwd: { validator: validRePwd, trigger: ['blur', 'change'] },
}
// 点击修改密码
const updatePwd = () => {
  showModal.value = true
}
// 关闭弹层
const closeModal = () => {
  showModal.value = false
  pwdRef.value.resetFields()
  pwdRef.value.clearValidate()
}
// 确认修改
const confirmUpdate = async () => {
  pwdRef.value.validate()
  const res = await updatePwdService(pwdForm.value)
  if (res.code === '0') {
    uni.showToast({
      title: '修改成功,请重新登录',
      icon: 'none',
    })
    setTimeout(() => {
      // 清空用户信息
      userStore.setUserInfo({})
      // 跳转到登录页
      uni.reLaunch({
        url: '/pages/loginAndRegister/loginAndRegister',
      })
    }, 1200)
  } else {
    uni.showToast({
      title: res.message,
      icon: 'none',
    })
  }
}
// 点击修改头像
const changeAvatar = () => {
  uni.chooseImage({
    count: 1,
    sizeType: ['original', 'compressed'], //原图和压缩图
    success: (res) => {
      const tempFilePaths = res.tempFilePaths
      // 上传图片
      uni.uploadFile({
        url: 'http://localhost:8080/api/avatar/uploadAvatar',
        filePath: tempFilePaths[0],
        name: 'file',
        header: { token },
        success: (res) => {
          formModel.value.avatar = JSON.parse(res.data).data
        },
        fail: (err) => {
          console.log(err)
        },
      })
    },
  })
}

// 点击修改保存信息
const submitChange = async () => {
  const res = await updateUserInfo(formModel.value)
  userStore.setUserInfo(formModel.value)
  if (res.code === '0') {
    uni.showToast({
      title: '修改成功',
      icon: 'success',
    })
  } else {
    uni.showToast({
      title: res.message,
      icon: 'none',
    })
  }
}
</script>

<style lang="scss" scoped>
.container {
  position: relative;
  .header-avatar {
    position: absolute;
    z-index: 1;
    left: 280rpx;
    top: -160rpx;
    width: 200rpx;
    height: 200rpx;
    border-radius: 50%;
    border: 1rpx solid #ffbbc0;
    margin: 50rpx auto;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: -40rpx;
    image {
      width: 200rpx;
      height: 200rpx;
      border-radius: 50%;
    }
  }
  .info-form {
    border-radius: 20rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    width: 600rpx;
    height: 600rpx;
    background-color: #ffffff;
    box-shadow: 0 0 30rpx rgba(0, 0, 0, 0.08);
    margin: 250rpx auto;
    .confirmBtn {
      width: 400rpx;
      height: 70rpx;
      margin: 0 auto;
      margin-top: 80rpx;
      border-radius: 30rpx;
      background: linear-gradient(to top right, #ffbbc0, #ffdbdd);
      font-size: 30rpx;
      color: #ffffff;
      font-weight: 400;
      letter-spacing: 20rpx;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
}
</style>
